package com.loyal.loyalerp.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.loyal.loyalerp.basedata.company.mapper.GyCompanyMapper;
import com.loyal.loyalerp.humenresource.role.mapper.GyRoleMapper;
import com.loyal.loyalerp.mapper.GyUserMapper;
import com.loyal.loyalerp.mapper.GyUserRoleMapper;
import com.loyal.loyalerp.model.GyUserRole;
import com.loyal.loyalerp.service.UserRoleService;

@Service
public class UserRoleServiceImpl implements UserRoleService{

	@Autowired
	GyUserRoleMapper gyUserRoleMapper;
	@Autowired
	GyRoleMapper roleMapper;
	@Autowired
	GyUserMapper userMapper;
	@Autowired
	GyCompanyMapper companyMapper;

	@Override
	public List<GyUserRole> listAll() {
		return gyUserRoleMapper.listAll();
	}

	@Override
	public GyUserRole selectByPrimaryKey(Integer id) {
		return gyUserRoleMapper.selectByPrimaryKey(id);
	}

	@Override
	public Map<String, Integer> getID(String usercode, String rolename,String name) {
		int userId = userMapper.selectUserIDByUserCode(usercode);
		int roleId = roleMapper.selectRoleIDByRoleName(rolename);
		int companyId = companyMapper.selectCompanyIDByName(name);
		Map<String,Integer> map = new HashMap<String,Integer>();
		map.put("userId", userId);
		map.put("roleId", roleId);
		map.put("companyId", companyId);
		return map;
	}

	@Override
	public int insertUserRole(GyUserRole gyUserRole) {
		try {
			if(gyUserRole.checkObjFieldIsNull(gyUserRole)) {
				return gyUserRoleMapper.insertSelective(gyUserRole);
			}else {
				return gyUserRoleMapper.insert(gyUserRole);
			}
		} catch (IllegalArgumentException | IllegalAccessException e) {
			e.printStackTrace();
		}
		return 0;
	}

	@Override
	public boolean EditRole(int id) {
		try {
			GyUserRole gyUserRole = gyUserRoleMapper.selectByPrimaryKey(id);
			gyUserRoleMapper.updateByPrimaryKeySelective(gyUserRole);
			return true;
		}catch(Exception e) {
			e.printStackTrace();
			throw new RuntimeException("发生异常，数据库回滚");
		}
	}
}
